package com.sites.cms.account;

import java.util.Date;
import java.util.List;

import com.jfinal.aop.Inject;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.sites.cms.permission.PermissionService;
import com.sites.common.SiteInfo;
import com.sites.common.model.Account;
import com.sites.common.model.Role;

/**
 * 用户账号处理服务层
 * 
 * @author zyg
 * 2020年1月4日 下午1:52:34
 */
public class AccountService {

	private Account dao = new Account().dao();
	private Role roleDao = new Role().dao();
	@Inject
	private PermissionService permSrv;
	
	/**
	 * 根据登录名查询用户
	 * @param name	登录名
	 * @return
	 */
	public Account getByName(String name){
		String sql = dao.getSql("account.getByName");
		return dao.findFirst(sql, name, SiteInfo.siteId);
	}
	
	/**
	 * 分页查询用户列表
	 * @param page		查询页码
	 * @param limit		每页显示条数
	 * @param nickName	要查询的昵称
	 * @param userName	要查询的登录名
	 * @param status	要查询的用户状态
	 * @return	Page<Account>
	 */
	@SuppressWarnings("unchecked")
	public Page<Account> queryAccountsPage(int page, int limit, String nickName, String userName, int status){
		Kv kv = Kv.create();
		kv.put("siteId", SiteInfo.siteId);
		kv.put("nickName", nickName);
		kv.put("userName", userName);
		kv.put("status", status);
		return dao.template("account.queryAccountsPage", kv).paginate(page, limit);
	}
	
	/**
	 * 保存用户
	 * @param account
	 * @return
	 */
	public Ret saveAccount(Account account){
		Ret ret = Ret.ok();
		Account temp = getByName(account.getUserName());
		if(temp != null){
			ret.setFail();
			ret.set(SiteInfo.msgKey, "登录名不可重复！");
			return ret;
		}
		account.setSiteId(SiteInfo.siteId);
		account.setPassword(HashKit.md5(account.getPassword()));//密码加密
		account.setStatus(SiteInfo.statusNormal);
		account.setCreateTime(new Date());
		account.save();
		ret.set(SiteInfo.msgKey, "用户添加成功！");
		return ret;
	}
	
	/**
	 * 根据id获取用户
	 * @param id
	 * @return
	 */
	public Account getById(int id){
		return dao.findById(id);
	}
	
	/**
	 * 更新用户信息
	 * @param account
	 * @return
	 */
	public Ret updateAccount(Account account){
		Ret ret = Ret.create();
		Account a = getById(account.getId());
		a.setNickName(account.getNickName());
		String pwd = account.getPassword();
		if(StrKit.notBlank(pwd)){
			a.setPassword(HashKit.md5(pwd));
		}
		a.setUpdateTime(new Date());
		boolean flag = a.update();
		if(flag){
			ret.setOk();
			ret.set(SiteInfo.msgKey, "更新成功");
		} else {
			ret.setFail();
			ret.set(SiteInfo.msgKey, "更新失败，请联系管理员！");
		}
		return ret;
	}
	
	/**
	 * 删除用户(逻辑删除)
	 * @param id
	 * @return
	 */
	public Ret deleteAccount(int id){
		Ret ret = Ret.create();
		Account account = dao.findById(id);
		account.setStatus(SiteInfo.statusDel);
		boolean flag = account.update();
		if(flag){
			ret.setOk();
			ret.set(SiteInfo.msgKey, "删除成功");
		} else {
			ret.setFail();
			ret.set(SiteInfo.msgKey, "删除失败，请联系管理员");
		}
		return ret;
	}
	
	/**
	 * 获取用户角色
	 * @param id
	 * @return
	 */
	public List<Role> getAccountRoles(int id){
		String sql = dao.getSql("account.getAccountRoles");
		return roleDao.find(sql, id);
	}
	
	/**
	 * 在所有角色中标记用户已有的角色(主要便于前端页面展示)
	 * @param roleList			所有角色列表
	 * @param accountRoleList	用户已有角色列表
	 * @return
	 */
	public List<Role> markAccountRole(List<Role> roleList, List<Role> accountRoleList){
		int roleId, accountRoleId;
		for(Role role : roleList){
			roleId = role.getId();
			for(Role accountRole : accountRoleList){
				accountRoleId = accountRole.getId();
				if(roleId == accountRoleId){
					role.put("mark", "checked");
					continue;
				}
			}
		}
		return roleList;
	}
	
	/**
	 * 更新用户的角色
	 * @param accountId	用户id
	 * @param roleId	角色id
	 * @param checked	新增或删除
	 * @return
	 */
	public Ret updateAccountRole(int accountId, int roleId, boolean checked){
		Ret ret = Ret.ok();
		String addSql = dao.getSql("account.addRole");
		String delSql = dao.getSql("account.delRole");
		int nums = 0;
		if(checked){
			nums = Db.update(addSql, accountId, roleId);
		} else {
			nums = Db.delete(delSql, accountId, roleId);
		}
		if(nums <= 0){
			ret.setFail();
			ret.set(SiteInfo.msgKey, "角色分配失败，请联系管理员！");
		} else {
			//手动清理用户缓存
			permSrv.clearAccPermCache(accountId);
		}
		return ret;
	}
	
	public Account getAdmin(){
		String sql = dao.getSql("account.getAdmin");
		return dao.findFirst(sql, SiteInfo.adminName);
	}
	
	public Ret updatePwd(int id, String password){
		Ret ret = Ret.create();
		Account temp = getById(id);
		String pwd = HashKit.md5(password);
		temp.setPassword(pwd);
		boolean flag = temp.update();
		if(flag){
			ret.setOk();
			ret.set(SiteInfo.msgKey, "更新成功");
		} else {
			ret.setFail();
			ret.set(SiteInfo.msgKey, "更新失败，请联系管理员！");
		}
		return ret;
	}
	
	/**
	 * 查询当前站点所有用户
	 * 
	 * @return
	 */
	public List<Account> queryAllAccounts(){
		return dao.template("account.queryAllAccounts", Kv.by("siteId", SiteInfo.siteId)).find();
	}
	

	/**
	 * 判断用户是否是超级管理员
	 * 
	 * @param account
	 * @return
	 */
	public boolean isAdmin(Account account) {
		return SiteInfo.adminName.equals(account.getUserName());
	}

	/**
	 * 删除站点下的用户角色
	 *
	 * @param siteId
	 * @return
	 */
	public Ret deleteSiteAccountRole(int siteId){
		Ret ret = Ret.ok();
		String sql = dao.getSql("account.deleteSiteAccountRole");
		Db.delete(sql, siteId);
		return ret;
	}

	/**
	 * 删除指定站点下的用户信息
	 *
	 * @param siteId
	 * @return
	 */
	public Ret deleteSiteAccount(int siteId){
		Ret ret = Ret.ok();
		String sql = dao.getSql("account.deleteSiteAccount");
		Db.delete(sql, siteId);
		return ret;
	}
}
